package com.omega.framework.common.util;

import com.omega.framework.common.util.thread.ThreadPoolUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.util.function.Consumer;

/**
 * 事务工具类
 *
 * @author Lv.
 * @date 2023/1/3 17:18
 */
@Slf4j
public class TransactionalUtils {

    /**
     * 事物提交后执行
     *
     * @param param   参数
     * @param process 执行方法
     * @param <T>     参数类型
     */
    public static <T> void afterCommit(T param, Consumer<T> process) {
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCommit() {
                process.accept(param);
            }
        });
    }

    /**
     * 事物提交后异步执行
     *
     * @param command Runnable
     */
    public static void afterCommit(Runnable command) {
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCommit() {
                ThreadPoolUtil.execute(command);
            }
        });
    }
}
